package com.demiroot.server;

import java.io.OutputStream;
import java.net.URL;
import java.net.URLConnection;
import java.util.Map.Entry;

public class ProxyRequest {
	private OutputStream out;
	private HTTPResquest request;	
	private ProxyIntercept pi;
	
	public ProxyRequest(OutputStream out, HTTPResquest request, ProxyIntercept pi) {
		this.out = out;
		this.request = request;
		this.pi = pi;
	}
	
	public void run() {
		try {
			request = pi.modifyOutgoingRequest(request);
			//fix up the header data to handle an incomming request
			URLConnection con = new URL(request.getHeader().getURI()).openConnection();
			for (Entry<HeaderData.HeaderField, String> entry : request.getHeader().getMap().entrySet()) {
				con.addRequestProperty(entry.getKey().name(), entry.getValue());
			}

			//build this object with the data from 
			//con methods.
			
			String sHead="";
			try {
				con.connect();
				sHead += "HTTP/1.1 200 OK";
				sHead += Server.ENDL;	
				sHead += "Content-Encoding:" + con.getContentEncoding();
				sHead += Server.ENDL;
				sHead += "Content-Length:" + con.getContentLength();
				
				sHead += Server.ENDL + Server.ENDL;	
				
			} catch (Exception e) {
				sHead = "HTTP/1.1 500 Server Error";
				sHead += Server.ENDL + Server.ENDL;				
			}
			
			HeaderData rHead = new HeaderData(sHead);
			rHead = pi.modifyReturningHeader(rHead);
			rHead.toString();
			out.write(ServerUtils.stringToByteArray("HTTP/1.1 200 OK"));
			out.write(ServerUtils.stringToByteArray(Server.ENDL));
			out.write(ServerUtils.stringToByteArray(rHead.toString()));
			out.write(ServerUtils.stringToByteArray(Server.ENDL + Server.ENDL));
			
			Logger.log("proxy", "HTTP/1.1 200 OK\n" + rHead.toString() + "\n");
			
			pi.modifiyContents(con.getInputStream(), out);
		} catch (Exception e) {
			System.err.println("Error proxy'n:");
			e.printStackTrace();
		}
	}
	
}
